import client.Client;
import marketdepth.MarketDepth;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

public class Server implements Runnable{
    private static Logger log = Logger.getLogger(Server.class.getName());
    private static final int PORT = 2004;

    private final ExecutorService threadPool = Executors.newCachedThreadPool();
    private final String[] sharesNames;
    private final MarketDepth marketDepth;

    public Server(String[] sharesNames) {
        log.info("Start server init");
        this.sharesNames = sharesNames;
        marketDepth = new MarketDepth(this.sharesNames);
        Thread marketDepthThread = new Thread(marketDepth);
        marketDepthThread.start();
    }

    @Override
    public void run() {
        log.info("Run server");
        ServerSocket listener = null;
        try {
            listener = new ServerSocket(PORT);
            while (true) {
                try {
                    final Socket connection = listener.accept();
                    threadPool.submit(new Client(connection, marketDepth));
                    log.info("New client will be connected");
                } catch (IOException e) {
                    log.info("Somebody tried to connect but failed because of " + e.getMessage());
                }
            }
        } catch (IOException e) {
            log.info("Server down because of" + e.getMessage());
        } finally {
            threadPool.shutdown();
            try {
                if (listener != null) {
                    listener.close();
                }
            } catch (IOException e) {
                log.info("Can't close server socket because of" + e.getMessage());
            }
        }
    }
}